import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Music from '@/views/Music'
import Users from '@/views/Users'
import store from '../store'

Vue.use(VueRouter)
// 动态路由匹配
// /user/1
// /user/2
// 只需添加如下代码即可
// const VueRouterPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(to) {
//   return VueRouterPush.call(this, to).catch(err => err)
// }

  const routes = [
  {
    path: '/',
    redirect:"/home",
    component: Home,
    children:[
      // {
      //   path:'home',
      //   component: () => import( '@/views/Home/ProductList.vue')
      // },
      {
        path:'home/productList',
        alias:'home',
        component: () => import( '@/views/Home/ProductList.vue')
      },
      {
        path:'home/productManage',
        component: () => import( '@/views/Home/ProductManage.vue'),
        meta:{requiresAuth: true},
      },
      {
        path:'home/shoppingCart',
        component: () => import( '@/views/Home/ShoppingCart.vue')
      },
    ],
  },
  {
    path: '/music',
    name: 'Music',
    component: Music,
  },
  {
    path: '/users/login',
    name: 'Users',
    component: Users,
  }
]

// 路由报错问题解决方案 ：Error: Avoided redundant navigation to current location
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}


const router = new VueRouter({
  mode: 'history',
  routes,
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if(store.state.users =='admin'){
      next()
    }else{
      next({
        path: './users/login',
        // query: { redirect: to.fullPath }
        query: { redirect: to.meta.redirect }
      })
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router;